package com.carson.data.zuul.filter;

import com.carson.data.zuul.config.DataFilterConfig;
import com.carson.data.zuul.util.AESUtil;
import com.carson.data.zuul.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;

@Component
public class PostLoginFilter extends ZuulFilter {
    private static Logger log = LoggerFactory.getLogger(PostLoginFilter.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private DataFilterConfig dataFilterConfig;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * pre：路由之前
     * routing：路由之时
     * post： 路由之后
     * error：发送错误调用
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
     * filterOrder：过滤的顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 3;
    }

    /**
     * shouldFilter：这里可以写逻辑判断，是否要过滤，本文true,永远过滤
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        // 获取到request
        RequestContext ctx = RequestContext.getCurrentContext();
        if (Boolean.FALSE.equals(ctx.get("isSuccess"))) {
            return false;
        }

        HttpServletRequest request = ctx.getRequest();
        if (dataFilterConfig.getLoginUri().contains(request.getRequestURI())) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() {
        RequestContext context = getCurrentContext();
        int statusCode = context.getResponseStatusCode();
        if (statusCode != 200) return null;
        String token = jwtUtil.createJWT(60000, new HashMap<>());
        context.addZuulResponseHeader("token", token);
        return null;
    }
}
